from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
import time
from datetime import datetime


def cron_job_example():
    """Cron表达式任务示例"""
    print(f"[{datetime.now()}] Cron任务执行")


def setup_apscheduler_with_cron():
    """使用APScheduler配置Cron表达式任务"""
    scheduler = BackgroundScheduler()

    # 1. 每天9点执行
    scheduler.add_job(
        cron_job_example,
        trigger=CronTrigger(hour=9, minute=0),
        id='daily_9am'
    )

    # 2. 每周一9点执行
    scheduler.add_job(
        cron_job_example,
        trigger=CronTrigger(day_of_week='mon', hour=9, minute=0),
        id='weekly_monday_9am'
    )

    # 3. 每月1号8点执行
    scheduler.add_job(
        cron_job_example,
        trigger=CronTrigger(day=1, hour=8, minute=0),
        id='monthly_1st_8am'
    )

    # 4. 复杂的Cron表达式
    scheduler.add_job(
        cron_job_example,
        trigger=CronTrigger.from_crontab('0 9,14,18 * * 1-5'),  # 工作日9点、14点、18点
        id='complex_cron'
    )

    # 5. 每5分钟执行
    scheduler.add_job(
        cron_job_example,
        trigger=CronTrigger(minute='*/5'),
        id='every_5_minutes'
    )

    scheduler.start()
    return scheduler


# 使用示例
scheduler = setup_apscheduler_with_cron()
print("APScheduler已启动，支持Cron表达式")

try:
    # 保持程序运行
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    scheduler.shutdown()
    print("调度器已关闭")